<?php

class BlogController extends Zend_Controller_Action
{

    public function init()
    {
        // 获取身份
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()){
            $this->identity = $auth->getIdentity();
        }
        
        $this->_helper->cache(array('index', 'view'), array('gook'));
    }
    
    public function indexAction()
    {
        $tagName = $this->_request->getParam('tag_name');
        $categoryId = $this->_request->getParam('category_id');
        // 博客列表
        $modelBlog = new Ms_Model_Page();
        $where = array('type'=>'blog');
        if ($categoryId) {
            $where['cid'] = $categoryId;
        }
        if ($tagName) {
            $where['tag_name'] = $tagName;
        }
        $blogs = $modelBlog->getPages($where);

        $paginator = new Zend_Paginator($blogs);
        $paginator->setItemCountPerPage(4);
        $paginator->setPageRange(5);
        // 获得当前显示的页码
        $page = $this->_request->getParam('page');
        $paginator->setCurrentPageNumber($page);
        // 渲染到视图
        $this->view->blogs = $paginator;
    }

    public function createAction()
    {
        if (!$this->identity->id){
            $this->_redirect('/user/login');
        }
        $formBlog = new Ms_Form_Blog();
        if ($this->getRequest()->isPost()){
            if ($formBlog->isValid($_POST)){
                $blogData = $formBlog->getValues();
                $blogData['uid'] = $this->identity->id;
                $blogData['type'] = 'blog';
                $blogData['createtime'] = time();
                $blogData['updatetime'] = time();
                $tags = str_replace("，", ",", $blogData['tags']);
                unset($blogData['tags']);
                unset($blogData['提交']);
                
                $modelBlog = new Ms_Model_Page();
                $newBlog = $modelBlog->createPage($blogData);
                
                if ($newBlog){
                    if ($tags != null){
                        $modelTags = new Ms_Model_Tags();
                        $modelTags->createTags($newBlog, $tags);
                        $modelTagsTotal = new Ms_Model_TagsTotal();
                        $arrTags = explode(",", $tags);
                        if (count($arrTags) > 0){
                            foreach ($arrTags as $value){
                                $modelTagsTotal->createTag($value);
                            }
                        }
                        else{
                            $modelTagsTotal->createTag($tags);
                        }
                        
                    }
                    $this->_redirect('blog/view/id/'.$newBlog);
                }
            }
        }
        $this->view->formBlog = $formBlog;
    }

    public function updateAction()
    {
        if (!$this->identity->id){
            $this->_redirect('/user/login');
        }
        $id = $this->_request->getParam('id');
        $modelBlog = new Ms_Model_Page();
        $formBlog = new Ms_Form_Blog();
        if ($this->getRequest()->isPost()){
            if ($formBlog->isValid($_POST)){
                $blogData = $formBlog->getValues();
                $blogData['uid'] = $this->identity->id;
                $blogData['type'] = 'blog';
                $blogData['updatetime'] = time();
                $tags = str_replace("，", ",", $blogData['tags']);
                unset($blogData['tags']);
                unset($blogData['提交']);
                
                $updateBlog = $modelBlog->updatePage($id, $blogData);
                if ($updateBlog){
                    if ($tags != null){
                        $modelTags = new Ms_Model_Tags();
                        $modelTags->deleteTags($id); // 清空原tags
                        $modelTags->createTags($updateBlog, $tags);
                        $modelTagsTotal = new Ms_Model_TagsTotal();
                        $arrTags = explode(",", $tags);
                        if (count($arrTags) > 0){
                            foreach ($arrTags as $value){
                                $modelTagsTotal->cutTag($value); // 从total中减去
                                $modelTagsTotal->createTag($value); //重新创建
                            }
                        }
                        else{
                            $modelTagsTotal->createTag($tags);
                        }
                    }
                    $this->_redirect('/blog/view/id/'.$updateBlog);
                }
            }
        }
        else {
            $blog = $modelBlog->getPage($id);
            if ($this->identity->id != $blog->uid){
                echo "你不是本博客的作者，不能对本博客进行编辑操作。";
                exit();
            }
            
            $arrBlog = $blog->toArray();
            // 该blog的tags
            $modelTags = new Ms_Model_Tags();
            $where = array('blog_id'=>$id);
            $tags = $modelTags->getTags($where);
            if (count($tags) > 0){
                $strTags = '';
                foreach ($tags as $tag){
                    $strTags .= $tag->tag.",";
                }
                $strTags = rtrim($strTags, ",");
            } else {
                $strTags = '';
            }
            $arrBlog['tags'] = $strTags;
            
            $formBlog->populate($arrBlog);
        }
        $this->view->formBlog = $formBlog;
    }

    public function viewAction()
    {
        $id = $this->_request->getParam('id');
        
        $modelBlog = new Ms_Model_Page();
        $blog = $modelBlog->getPage($id);
        if ($blog){
            $this->view->blog = $blog;
            
            // tags
            $modelTags = new Ms_Model_Tags();
            $where = array('blog_id' => $id);
            $tags = $modelTags->getTags($where);
            if ($tags){
                $this->view->tags = $tags;
            }
            
            // 评论列表
            $modelComment = new Ms_Model_Comment();
            $comments = $modelComment->getComments($id);
            $this->view->comments = $comments;
            $formComment = new Ms_Form_Nologincomment();
    
            if ($this->_request->isPost()){
                $dataComment = $this->_request->getPost(); // 获取表单提交值
                if ($_SESSION['captcha']['code'] != $dataComment['captcha_code']) {
                    $dataComment['captcha_code'] = '';
                }
                if ($formComment->isValid($dataComment)){
                    $_SESSION['captcha'] = null;
                    // 将经过验证的数据写入数据库
                    $newComment = $modelComment->createComment( $id, $dataComment['name'], $dataComment['email'], $dataComment['comment']);
                    if($newComment) {
                        $this->_redirect('/blog/view/id/'.$id);
                    }
                }
            }
            
            //快速评论
            $this->view->nologincomment = $formComment;
            $this->view->captcha_url = $this->getcaptcha();;
        }
        else{
            echo "该博客文章不存在！";
        }
    }

    public function deleteAction()
    {
        $id = $this->_request->getParam('id');
        $modelBlog = new Ms_Model_Page();
        $modelBlog->deletePage($id);
        $this->_redirect('/blog');
    }
    
    public function captchaAction() {
        echo $this->getcaptcha();
        exit;
    }
    /**
     * 生成验证码
     */
    private function getcaptcha() {
        $this->_captcha_session = new Zend_Session_Namespace('captcha'); //在默认构造函数里实例化
    
        $captcha = new Zend_Captcha_Image(array(
            'font'=>'images/FreeSerifBold.ttf',     // 字体文件路径
            'session' => $this->_captcha_session,    // 验证码session值
            'fontsize' => 15, // 字号
            'imgdir' => 'images/code/',    // 验证码图片存放位置
            'width' => 120,    // 图片宽
            'height' => 30,    // 图片高
            'gcFreq' => 3,    // 删除生成的旧的验证码图片的随机几率
            'dotNoiseLevel' => 5,    // 躁点数
            'lineNoiseLevel' => 1,    // 线条
            'wordlen'=>5 )    // 字母数
        );
        $captcha->generate(); // 生成图片
        $_SESSION['captcha']['code'] = $captcha->getWord();
        return '/'.$captcha->getImgDir().$captcha->getId().$captcha->getSuffix();
    }
}
